<?php
declare (strict_types=1);
namespace app\admin\model;
use think\Model;
use think\db\Query;
use app\admin\service\AdminUser as AdminUserService;
/**
 * 模型基类
 * Class BaseModel
 * @package app\common\model
 */
class BaseModel extends Model
{
    // 错误信息
    protected $error = '';

    /**
     * [userInfo 登录信息]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function userInfo()
    {
        // 返回用户登录信息
        $getLoginInfo = AdminUserService::getLoginInfo();
        return isset($getLoginInfo['user'])?$getLoginInfo['user']:'';
    }
    
    /**
     * 返回错误信息
     * @return string
     */
    public function getError()
    {
        return empty($this->error) ? false : $this->error;
    }
    
    /**
     * 查找单条记录
     * @param $data
     * @param array $with
     */
    public function get($data, $with = [],$hidden = [])
    {
        try {
            $query = $this->with($with);
            return is_array($data) ? $query->where($data)->hidden($hidden)->find() : $query->hidden($hidden)->find((int)$data);
        } catch (\Exception $e) {
            return false;
        }
    }
    /**
     * 字段值增长
     * @param array|int|bool $where
     * @param string $field
     * @param float $step
     */
    protected function setInc($where, string $field, float $step = 1)
    {
        if (is_numeric($where)) {
            $where = [$this->getPk() => (int)$where];
        }
        return $this->where($where)->inc($field, $step)->update();
    }

    /**
     * 字段值消减
     * @param array|int|bool $where
     * @param string $field
     * @param float $step
     */
    protected function setDec($where, string $field, float $step = 1)
    {
        if (is_numeric($where)) {
            $where = [$this->getPk() => (int)$where];
        }
        return $this->where($where)->dec($field, $step)->update();
    }

    /**
     * 设置默认的检索数据
     * @param array $param
     * @param array $default
     */
    protected function setDefaultValue(array $param, array $default = [])
    {
        $res = array_merge($default, $param);
        foreach ($param as $field => $val) {
            // 不存在默认值跳出循环
            if (!isset($default[$field])) continue;
            // 如果传参为空, 设置默认值
            if (empty($val) && $val !== '0') {
                $res[$field] = $default[$field];
            }
        }
        return $res;
    }
}
